<?php
namespace app\admin\controller;
use app\admin\validate\Role as RoleValidate;
use think\Db;
use think\Exception;

	class Role extends Base
	{
	
		/**
		 * 角色管理
		 */
		public function Role(){	
			//dump(input());	
			$condition=[];
			if(input('username')){
				$condition[]=['role_name','like',"%".input('username')."%"];
			}
			$info = db('admin_role')
				->where($condition)
				->paginate([
					'list_rows'=>3,
					'query'=>input('param.'),
				]);
			$list = db('admin_role')
				->field('r.role_id,r.role_name,r.role_desc,s.title')
				->alias('r')
				->join('tp_access a','a.role_id=r.role_id')
				->join('tp_system_module s','a.right_id=s.mod_id')
				->select();
			$this->assign('list',$list);
			$this->assign('info',$info);
			return $this->fetch();
		}
		/**
		 * 角色添加
		 */
		public function add(){
			$data=model('SystemModule')->getAllMenu();
			$this->assign($data);
			if($this->request->isPost()){
				$validate = new RoleValidate;
				if(!$validate->check(input())){
					return $this->error($validate->getError());
				}
				Db::startTrans();
	    		try{
	    			//第一步:把角色添加到数据库
	    			$insertid = db('admin_role')->insertGetId([
	    				'role_name' => input("post.role_name"),
	    				'role_desc' => input("post.roledesc")
	    			]);
	    			//第二步:把角色和权限的关系添加到数据库
	    			if(!$insertid){
	    				throw new Exception("添加失败",2);
	    			}
	    			$access = input("post.roleaccess/a");
	    			foreach($access as $v){
	    				$res=db('access')->insert([
	    					'role_id' => $insertid,
	    					'right_id'=> $v
	    				]);
	    			}
	    			//提交事务
	    			Db::commit();
	    			throw new Exception("添加成功",1);
	    		}catch (\Exception $e){
	    			Db::rollback();
	    			if($e->getCode()===1){
	    				return $this->success($e->getMessage());
	    			}else{
	    				return $this->error($e->getMessage());
	    			}
	    		}
			}else{
				// dump($data);die;
				return $this->fetch();
			}
			
		}
		/**
		 * 角色编辑
		 */
		public function edit(){
			$list=model('Access')->getAllPer(input('param.role_id'));
			if($this->request->isPost()){
				$validate = new RoleValidate;
				if(!$validate->check(input())){
					return $this->error($validate->getError());
				}
				
				Db::startTrans();
    			try{
    				//第一步:修改角色数据库
    				$data = [
	    				'role_name' => input("post.role_name"),
	    				'role_desc' => input("post.roledesc")
	    			];
    				$res = model('AdminRole')->rolup(input('param.role_id'),$data);
    				if($res != true){
    					throw new Exception("修改失败",2);
    				}
    				//第二步:添加新增权限
    				$new = input('post.roleaccess');
    				$old = $list;
    				$res = array_diff($new, $old);
					if(!empty($res)){
						foreach ($res as $v) {
							$a[]=[
								'right_id'=>$v,
								'role_id'=>input("param.role_id")
							];
						}
		    			$ins = db('access')->insertAll($a);
		    			if($ins==0){
		    				throw new Exception("修改失败",2);
		    			}
	    			}
	    			//第三步:删除多余权限
					$res = array_diff($old, $new);
					if(!empty($res)){
						$b='';
						foreach ($res as $v) {
							$b.=$v.",";
						}
						$b = substr($b,0,-1);
		    			$del = db('access')->where("right_id in(".$b.") and role_id=".input("param.role_id"))->delete();
		    			if($del==0){
		    				throw new Exception("修改失败",2);
		    			}
	    			}
	    			//提交事务
	    			Db::commit();
	    			throw new Exception("修改成功",1);
    			}catch (\Exception $e){
	    			Db::rollback();
	    			if($e->getCode()===1){
	    				return $this->success($e->getMessage());
	    			}else{
	    				return $this->error($e->getMessage());
	    			}
	    		}
			}else{
				$data=model('SystemModule')->getAllMenu();
				$info=model('AdminRole')->getCon(input('param.role_id'));
				$this->assign($data);
				$this->assign('list',$list);
				$this->assign('info',$info);
				return $this->fetch();
			}		
		}
		/**
		 * 角色删除
		 */
		public function del(){
			$id=input('post.id');
			if(!empty(input('post.allid'))){
	    		$id=substr(input('post.allid'),0,-1);
	    	}
	    	Db::startTrans();
			try{
				//第一步:删除角色表
				$res=db('admin_role')->where("role_id",'in',$id)->delete();
				if($res==0){
					throw new Exception("删除失败",2);
				}
				//第二步:删除权限表中相关数据
				$res=db('access')->where("role_id",'in',$id)->delete();
				if($res==0){
					throw new Exception("删除失败",2);
				}
				//第三步:清空管理员表中的权限
				$res=db('admin')->where("role_id",'in',$id)->update(['role_id'=>'']);
				//提交事务
				Db::commit();
				throw new Exception("删除成功",1);
			}catch (\Exception $e){
				Db::rollback();
				if($e->getCode()===1){
					return $this->success($e->getMessage());
				}else{
					return $this->error($e->getMessage());
				}
			}
		}
	
	}